/*
 * Copyright (c) 2015. For Intelligent Group.
 */

package com.intelligent.ispc.security;

import com.intelligent.ispc.common.dto.JsonResponseDto;
import com.intelligent.ispc.common.mapper.JsonMapper;
import com.intelligent.ispc.common.utils.ExceptionMessages;
import com.intelligent.ispc.core.dto.SecurityUserDto;
import com.intelligent.ispc.core.dto.UserDto;
import com.intelligent.ispc.core.service.SecurityService;
import com.intelligent.ispc.utils.SystemConfig;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by yangli on 2015-08-19.
 */
public class ShiroFilter extends FormAuthenticationFilter {
    private static final Logger log = LoggerFactory.getLogger(ShiroFilter.class);

    @Autowired
    private SecurityService securityService;

    @Autowired
    protected SystemConfig systemConfig;

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        if ("XMLHttpRequest".equalsIgnoreCase(httpServletRequest.getHeader("X-Requested-With"))) {
            httpServletResponse.setCharacterEncoding("UTF-8");
            PrintWriter out = httpServletResponse.getWriter();
            String json = new JsonMapper().toJson(JsonResponseDto.SUCCESS());
            out.println(json);
            out.flush();
            out.close();
        } else {

            if (subject.getPrincipal() != null) {
                if (subject != null && subject.isAuthenticated()) {
                    SecurityUserDto securityUserDto = (SecurityUserDto) subject.getPrincipal();

                    UserDto dto = securityService.refreshLoginTime(securityUserDto.getLoginName());
                    securityUserDto.setLastLoginTime(dto.getLastLoginTime());
                    securityUserDto.setPageSize(systemConfig.getPageSize());
                    subject.getSession().setAttribute("user", securityUserDto);

                }
            }

            issueSuccessRedirect(request, response);
        }

        return false;
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        if ("XMLHttpRequest".equalsIgnoreCase(httpServletRequest.getHeader("X-Requested-With"))) {

            try {
                httpServletResponse.setCharacterEncoding("UTF-8");
                if (httpServletResponse != null) {
                    httpServletResponse.setHeader("Cache-Control", "no-cache");
                    httpServletResponse.setHeader("Pragma", "no-cache");
                    httpServletResponse.setHeader("Expires", "-1");
                }

                PrintWriter out = httpServletResponse.getWriter();
                String message = e.getClass().getSimpleName();
                JsonMapper jsonMapper = new JsonMapper();
                if ("IncorrectCredentialsException".equals(message)) {
                    //wrong password
                    out.println(jsonMapper.toJson(JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_SECURITY_INCORRECT_CREDENTIALS)));
                } else if ("UnknownAccountException".equals(message)) {
                    out.println(jsonMapper.toJson(JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_SECURITY_UNKNOWN_ACCOUNT)));
                } else if ("LockedAccountException".equals(message)) {
                    out.println(jsonMapper.toJson(JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_SECURITY_LOCKED_ACCOUNT)));
                } else {
                    out.println(jsonMapper.toJson(JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_SYSTEM)));
                }
                out.flush();
                out.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } else {
            setFailureAttribute(request, e);
            return true;
        }

        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                if (log.isTraceEnabled()) {
                    log.trace("Login submission detected. Attempting to execute login.");
                }
                return executeLogin(request, response);
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("Login page view.");
                }
                return true;
            }
        } else {
            if (log.isTraceEnabled()) {
                log.trace("Attempting to access a path which requires authentication. Forwarding to the "
                        + "Authentication url [" + getLoginUrl() + "]");
            }
            if (!"XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"))) {
                saveRequestAndRedirectToLogin(request, response);
            } else {
                response.setCharacterEncoding("UTF-8");
                HttpServletResponse res = WebUtils.toHttp(response);
                res.sendError(401);
                return false;
            }

            return false;
        }
    }
}
